package MyDP;

import java.util.Arrays;

/**
 * 300. 最长递增子序列
 * 需要输出其中一个最长递增子序列
 */
public class Leetcode0300_2 {

    //返回一个最长递增子序列
    public static int[] printLIS(int[] nums) {
        if (nums.length == 0) return new int[0];
        // dp 数组
        int[] dp = new int[nums.length];

        // 记录他的前一位是谁
        int[] pre = new int[nums.length];

        // 初始化
        int res = 0;
        Arrays.fill(dp, 1);
        Arrays.fill(pre, -1);
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i] && dp[i] < dp[j] + 1){
                    dp[i] =  dp[j] + 1;
                    pre[i] = j;
                }
            }
            res = Math.max(res, dp[i]);
        }

        int max_index = 0;
        for(int i=0 ;i<nums.length; i++) {
            if(dp[i] == res){
                max_index = i;
                break;
            }
        }
//        for(int ss : dp){
//            System.out.print(ss + " ");
//        }
//        System.out.println("\n");
//        for(int ss : pre){
//            System.out.print(ss + " ");
//        }
//        System.out.println('\n');

        int [] ans = new int[res];
        int cur = res-1;

        while (max_index!=-1){
//            System.out.println(nums[max_index]);
            ans[cur--] = nums[max_index];
            max_index = pre[max_index];
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1,3,2,25,6,7,9};
        int[] ints = printLIS(nums);
        for(int ss: ints){
            System.out.print(ss + " ");
        }
    }
}
